package com.example.homework7;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class sharestorage extends Fragment {
    public sharestorage(){
        super(R.layout.sharestorage);
    }

    private String FILE_NAME = "sharePreference.txt";
    private EditText NumberText;
    private EditText PasswordText;

    @Override
    public void onViewCreated(@NonNull View view, @NonNull Bundle saveInstanceState){
        super.onViewCreated(view,saveInstanceState);

        //需给输入框查找组件，不然会闪退
        NumberText = getView().findViewById(R.id.NumberText);
        PasswordText = getView().findViewById(R.id.PasswordText);

        //写入
        SharedPreferences settings = getActivity().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        getView().findViewById(R.id.LoginButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("countNumber",NumberText.getText().toString());
                editor.putString("password",PasswordText.getText().toString());
                try {
                    MessageDigest md = MessageDigest.getInstance("SHA-256");
                    md.update(NumberText.getText().toString().getBytes(Charset.forName("UTF-8")));
                    editor.putString("password",String.valueOf(md.digest()));
                }catch (NoSuchAlgorithmException e){
                    e.printStackTrace();
                }
                editor.apply();
                Toast.makeText(getActivity(),"登陆成功",Toast.LENGTH_SHORT).show();
            }
        });

        //读取
        NumberText.setText(settings.getString("countNumber",""));
        PasswordText.setText(settings.getString("password", ""));
    }

}
